package com.yx.fsysserver.file.component;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 本地文件读写
 * Created by lichagnfeng on 2017/3/6.
 */
@Component
public class LocalFileAccessComp implements FileAccessComp {
    private Logger log = LoggerFactory.getLogger(LocalFileAccessComp.class);


    @Override
    public void write(File file, String savePath) throws Exception {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            String fileName = file.getName();
            this.write(fis,savePath,fileName);
        } catch (FileNotFoundException e) {
            throw e;
        } finally {
            if (fis!=null){
                fis.close();
            }
        }
    }

    @Override
    public void write(InputStream inputStream, String savePath, String fileName) throws Exception {

        FileOutputStream fos = null;
        try {
            File saveDir = new File(savePath);
            FileUtils.forceMkdir(saveDir);
            fos = new FileOutputStream(savePath+fileName);

            IOUtils.copy(inputStream,fos);

        }catch (Exception e){
            throw e;
        }finally {
            if (fos!=null){
                fos.close();
                fos = null;
            }
        }

    }

    @Override
    public void writeDir(File dirFile, String savePath) throws Exception {

        FileUtils.copyDirectory(dirFile,new File(savePath));
    }

    @Override
    public boolean delete(String filePath) throws Exception {
        File file = new File(filePath);
        boolean result = file.delete();
        String resultInfo = result?"delete "+filePath+" success.":"delete "+filePath+" fail.";
        log.info(resultInfo);
        return result;
    }

    @Override
    public InputStream read(String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists()){
            return null;
        }
        FileInputStream fis = new FileInputStream(filePath);

        return fis;
    }

    @Override
    public Long getFileLength(String filePath) {
        File file = new File(filePath);
        return file.length();
    }
}
